
package com.joysuch.wwyt.bp.service.impl;

import com.google.common.collect.Lists;
import com.joysuch.wwyt.bp.bean.*;
import com.joysuch.wwyt.bp.entity.*;
import com.joysuch.wwyt.bp.entity.contractor.BpContractor;
import com.joysuch.wwyt.bp.enums.DeviceFacilityTypes;
import com.joysuch.wwyt.bp.repository.*;
import com.joysuch.wwyt.bp.service.BpDeviceFacilityCollectionService;
import com.joysuch.wwyt.bp.service.BpStoreHouseService;
import com.joysuch.wwyt.core.bean.SimpleSelectListBean;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.entity.BaseUser;
import com.joysuch.wwyt.core.repository.BaseTypeGroupItemDao;
import com.joysuch.wwyt.core.repository.BaseUserDao;
import com.joysuch.wwyt.core.service.BaseAttachmentRepositoryService;
import com.joysuch.wwyt.core.service.BizCodeGeneratorFacade;
import com.joysuch.wwyt.mh.bean.MhMonitoringPointBean;
import com.joysuch.wwyt.mh.bean.MhMonitoringRealTimeListBean;
import com.joysuch.wwyt.mh.entity.MhMajorHazard;
import com.joysuch.wwyt.mh.entity.MhMajorHazardChemProduct;
import com.joysuch.wwyt.mh.entity.MhMonitoringPoint;
import com.joysuch.wwyt.mh.repository.MhMajorHazardChemProductDao;
import com.joysuch.wwyt.mh.repository.MhMajorHazardDao;
import com.joysuch.wwyt.mh.repository.MhMonitoringPointDao;
import com.joysuch.wwyt.mh.service.MhMonitoringPointService;
import com.joysuch.wwyt.risk.service.RiskDistrictService;
import com.joysuch.wwyt.util.PageableUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.transaction.Transactional;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class BpStoreHouseServiceImpl implements BpStoreHouseService {

    @Autowired
    private BpStoreHouseDao dao;
    @Autowired
    private BpMonitoringPointRelDao relDao;
    @Autowired
    private MhMonitoringPointService mhMonitoringPointService;
    @Autowired
    private BpDeviceFacilityCollectionService bpDeviceFacilityCollectionService;
    @Autowired
    private MhMajorHazardDao mhMajorHazardDao;
    @Autowired
    private BizCodeGeneratorFacade bizCodeGeneratorFacade;
    @Autowired
    private BpStoreMaterialTypeDao bpStoreMaterialTypeDao;
    @Autowired
    private BpStoreMaterialUnitDao bpStoreMaterialUnitDao;
    @Autowired
    private BpStoreMaterialDao bpStoreMaterialDao;
    @Autowired
    private MhMajorHazardChemProductDao mhMajorHazardChemProductDao;
    @Autowired
    private BpStoreMaterialRecordDao bpStoreMaterialRecordDao;
    @Autowired
    private BaseUserDao baseUserDao;
    @Autowired
    private BpContractorDao bpContractorDao;
    @Autowired
    private BaseAttachmentRepositoryService attachmentRepositoryService;
    @Autowired
    private MhMonitoringPointDao mhMonitoringPointDao;
    @Autowired
    private BaseTypeGroupItemDao baseTypeGroupItemDao;

    @Autowired
    private RiskDistrictService districtService;
    @Autowired
    private BpDepartDao bpDepartDao;

    @Override
    public Page list(Pageable of) {
        return dao.findAll(of);
    }

    /**
     * 增加仓库
     *
     * @param b
     */
    @Override
    public BpStoreHouse add(BpStoreHouseAddBean b) {
        BpStoreHouse h = new BpStoreHouse();
        if (StringUtils.isNotBlank(b.getName())) {
            List<BpStoreHouse> bhList = dao.findByNameAndTypeFlag(b.getName(), b.getTypeFlag());
            if (!CollectionUtils.isEmpty(bhList)) {
                throw new IllegalArgumentException("仓库名称已存在");
            }
        }
        BeanUtils.copyProperties(b, h);
        //库房编号
        if (StringUtils.isBlank(b.getCode())) {
            if (b.getParentId() != null) {
                BpStoreHouse parent = dao.getOne(b.getParentId());
                Integer no = parent.getChildNo();
                if (no == null) {
                    no = 1;
                }
                h.setChildNo(1);
                h.setCode(parent.getCode() + "-" + StringUtils.leftPad(no + "", 3, '0'));
                parent.setChildNo(no + 1);
                dao.save(parent);
            } else {
                String s = bizCodeGeneratorFacade.kuFang();
                h.setCode(s.substring(s.length() - 3, s.length()));
                h.setChildNo(1);
            }
        }
        if (b.getTypeFlag() == 0) {
            h.setHazardChemStoreFlag("N");
        } else if (b.getTypeFlag() == 1) {
            h.setHazardChemStoreFlag("Y");
        }
        BpStoreHouse save = dao.save(h);
        List<Long> pointId = b.getPointId();
        if (!CollectionUtils.isEmpty(pointId)) {
            for (Long aLong : pointId) {
                BpMonitoringPointRel bpMonitoringPointRel = new BpMonitoringPointRel();
                bpMonitoringPointRel.setRefType("store_house");
                bpMonitoringPointRel.setRefId(save.getId());
                bpMonitoringPointRel.setMonitoringPointId(aLong);
                String errorMessage = mhMonitoringPointService.checkMhMointPoint(aLong, save.getId());
                if (StringUtils.isNotBlank(errorMessage)) {
                    throw new IllegalArgumentException(errorMessage);
                }
                relDao.save(bpMonitoringPointRel);
            }
        }
        addOrUpdateDeviceFacilityCollection(save, pointId);
        return save;
    }

//    //判断监测点是否被其他库房绑定
//    private void checkHousePoint(BpStoreHouse save, Long pointId) {
//        MhMonitoringPoint mhMonitoringPoint = mhMonitoringPointDao.findById(pointId).get();
//        List<BpMonitoringPointRel> otherList = relDao.getOtherHousePointRelList(pointId, save.getCode().substring(0, 3));
//        if (!CollectionUtils.isEmpty(otherList)) {
//            throw new IllegalArgumentException(mhMonitoringPoint.getName() + "(" + mhMonitoringPoint.getPointCode() + ")已被:" + "仓库" + "关联");
//        }
//        if (save.getParentId() != null) {
//            List<BpMonitoringPointRel> broList = relDao.getBrotherHousePointRelList(save.getParentId(), pointId);
//            if (broList.size() > 1) {
//                throw new IllegalArgumentException(mhMonitoringPoint.getName() + "(" + mhMonitoringPoint.getPointCode() + ")已被:" + "仓库" + "关联");
//            }
//        }
//        String str = "";
//        List<BpMonitoringPointRel> pointList = relDao.findByMonitoringPointIdAndRefTypeNotLike(pointId, "store_house");
//        if (pointList.size() > 0) {
//            List<String> collect = pointList.stream().distinct().map(BpMonitoringPointRel::getRefType).collect(Collectors.toList());
//            if (collect.contains("production_facility")) {
//                str = str + "设备装置 ";
//            }
//            if (collect.contains("store_tank_area")) {
//                str = str + "储罐区 ";
//            }
//            if (collect.contains("store_tank")) {
//                str = str + "储罐 ";
//            }
//            if (collect.contains("manufacturing_tech")) {
//                str = str + "工艺流程 ";
//            }
//        }
//        if (StringUtils.isNotBlank(str)) {
//            throw new IllegalArgumentException(mhMonitoringPoint.getName() + "(" + mhMonitoringPoint.getPointCode() + ")已被:" + str + "关联");
//        }
//    }

    private void addOrUpdateDeviceFacilityCollection(BpStoreHouse save, List<Long> pointId) {
        // 保存到集中统一的表中
        BpDeviceFacilityCollection device = bpDeviceFacilityCollectionService.addOrUpdateOtherDevice(
                DeviceFacilityTypes.KU_FANG, save.getId(), save.getCode(), save.getName(), null,
                save.getMajorHazardId(), save.getLocation());
        // 绑定监测点
        if (!CollectionUtils.isEmpty(pointId)){
            bpDeviceFacilityCollectionService.bindDeviceAndMonitorPointsByIds(device, pointId);
        }
    }

    /**
     * 修改仓库
     *
     * @param b
     */
    @Override
    public BpStoreHouse edit(BpStoreHouseAddBean b) {
        relDao.deleteByRefTypeAndRefId("store_house", b.getId());
        BpStoreHouse h = dao.findById(b.getId()).get();
        String code = h.getCode();
        Long parentId = h.getParentId();
        BeanUtils.copyProperties(b, h);
        if (StringUtils.isBlank(b.getCode())) {
            h.setCode(code);
        }
        h.setParentId(parentId);
        if (b.getTypeFlag() == 0) {
            h.setHazardChemStoreFlag("N");
        } else if (b.getTypeFlag() == 1) {
            h.setHazardChemStoreFlag("Y");
        }
        BpStoreHouse save = dao.save(h);
        if (StringUtils.isNotBlank(b.getName())) {
            List<BpStoreHouse> bhList = dao.findByNameAndTypeFlag(b.getName(), b.getTypeFlag());
            if (bhList.size() > 1) {
                throw new IllegalArgumentException("仓库名称已存在");
            }
        }
        List<Long> pointId = b.getPointId();
        if (!CollectionUtils.isEmpty(pointId)) {
            for (Long aLong : pointId) {
                BpMonitoringPointRel bpMonitoringPointRel = new BpMonitoringPointRel();
                bpMonitoringPointRel.setRefType("store_house");
                bpMonitoringPointRel.setRefId(save.getId());
                bpMonitoringPointRel.setMonitoringPointId(aLong);
                String errorMessage = mhMonitoringPointService.checkMhMointPoint(aLong, save.getId());
                if (StringUtils.isNotBlank(errorMessage)) {
                    throw new IllegalArgumentException(errorMessage);
                }
                relDao.save(bpMonitoringPointRel);

            }
        }
        addOrUpdateDeviceFacilityCollection(save, pointId);
        return save;
    }

    /**
     * 删除仓库
     *
     * @param id
     */
    @Override
    public void delete(Long id) {
        List<BpStoreHouse> li = dao.findByParentId(id);
        List<BpStoreMaterial> lis = bpStoreMaterialDao.findByHouseId(id);
        if (!CollectionUtils.isEmpty(li)) {
            throw new IllegalArgumentException("请先删除该库房下的子库房");
        }
        if (!CollectionUtils.isEmpty(lis)) {
            throw new IllegalArgumentException("请先删除该库房下的物资");
        }
        relDao.deleteByRefTypeAndRefId("store_house", id);
        dao.deleteById(id);
        bpDeviceFacilityCollectionService.delteByDeviceTypeAndDeviceId(DeviceFacilityTypes.KU_FANG, id);
    }

    /**
     * 查看仓库
     *
     * @param id
     * @return
     */
    @Override
    public BpStoreHouseAddBean getById(Long id) {
        BpStoreHouse b = dao.getOne(id);
        List<BpMonitoringPointRel> all1 = relDao.findByRefTypeAndRefId("store_house", id);
        BpStoreHouseAddBean h = new BpStoreHouseAddBean();

        if (b.getAutoSprayFlag() != null) {
            if (b.getAutoSprayFlag().equals("Y")) {
                h.setAutoSprayFlag(b.getAutoSprayFlag());
                h.setAutoSprayFlagName("是");
            }
            if (b.getAutoSprayFlag().equals("N")) {
                h.setAutoSprayFlag(b.getAutoSprayFlag());
                h.setAutoSprayFlagName("否");
            }
        }

        h.setCode(b.getCode());
        h.setDesignStock(b.getDesignStock());
        h.setFireDangerType(b.getFireDangerType());
        if (b.getFireWallFlag() != null) {
            if (b.getFireWallFlag().equals("Y")) {
                h.setFireWallFlag(b.getFireWallFlag());
                h.setFireWallFlagName("有");
            }
            if (b.getFireWallFlag().equals("N")) {
                h.setFireWallFlag(b.getFireWallFlag());
                h.setFireWallFlagName("无");
            }
        }

        if (b.getHazardChemStoreFlag() != null) {
            if (b.getHazardChemStoreFlag().equals("Y")) {
                h.setHazardChemStoreFlag(b.getHazardChemStoreFlag());
                h.setHazardChemStoreFlagName("是");
            }
            if (b.getHazardChemStoreFlag().equals("N")) {
                h.setHazardChemStoreFlag(b.getHazardChemStoreFlag());
                h.setHazardChemStoreFlagName("否");
            }
        }
        // h.setHouseNo(b.getHouseNo());
        if (b.getHypertoxicHazardChemStoreFlag() != null) {
            if (b.getHypertoxicHazardChemStoreFlag().equals("Y")) {
                h.setHypertoxicHazardChemStoreFlag(b.getHypertoxicHazardChemStoreFlag());
                h.setHypertoxicHazardChemStoreFlagName("是");
            }
            if (b.getHypertoxicHazardChemStoreFlag().equals("N")) {
                h.setHypertoxicHazardChemStoreFlag(b.getHypertoxicHazardChemStoreFlag());
                h.setHypertoxicHazardChemStoreFlagName("否");
            }
        }
        h.setId(b.getId());
        h.setLocation(b.getLocation());
        h.setStartUseTime(b.getStartUseTime());
        if (b.getLowTemperatureStoreFlag() != null) {
            if (b.getLowTemperatureStoreFlag().equals("Y")) {
                h.setLowTemperatureStoreFlag(b.getLowTemperatureStoreFlag());
                h.setLowTemperatureStoreFlagName("是");
            }
            if (b.getLowTemperatureStoreFlag().equals("N")) {
                h.setLowTemperatureStoreFlag(b.getLowTemperatureStoreFlag());
                h.setLowTemperatureStoreFlagName("否");
            }
        }
        if (b.getMajorHazardId() != null) {
            MhMajorHazard one = mhMajorHazardDao.getOne(b.getMajorHazardId());
            if (one != null) {
                h.setMajorHazardUnit(one.getName());
            }
        }
        h.setMajorHazardId(b.getMajorHazardId());

        h.setMajorHazardUnitCode(b.getMajorHazardUnitCode());

        if (b.getMajorMonitoringChemFlag() != null) {
            if (b.getMajorMonitoringChemFlag().equals("Y")) {
                h.setMajorMonitoringChemFlag(b.getMajorMonitoringChemFlag());
                h.setMajorMonitoringChemFlagName("是");
            }
            if (b.getMajorMonitoringChemFlag().equals("N")) {
                h.setMajorMonitoringChemFlag(b.getMajorMonitoringChemFlag());
                h.setMajorMonitoringChemFlagName("否");
            }
        }
        h.setName(b.getName());
        h.setStartUseTime(b.getStartUseTime());
        h.setStoreHouseForm(b.getStoreHouseForm());
        h.setStoreHouseSize(b.getStoreHouseSize());
        ArrayList<MhMonitoringPointBean> objects = new ArrayList<>();
        if (all1 != null) {
            for (BpMonitoringPointRel bpMonitoringPointRel : all1) {
                if (bpMonitoringPointRel.getRefId() == b.getId()
                        && bpMonitoringPointRel.getRefType().equals("store_house")) {
                    MhMonitoringPointBean byId = mhMonitoringPointService
                            .getById(bpMonitoringPointRel.getMonitoringPointId());
                    objects.add(byId);
                }
            }
        }
        h.setParentId(b.getParentId());
        if (b.getParentId() != null) {
            h.setParentName(dao.getOne(b.getParentId()).getName());
        }
        h.setMhMonitoringPointBeans(objects);
        h.setTypeFlag(b.getTypeFlag());
        return h;
    }

    @Override
    public List<BpStoreHouseAddBean> getByIds(List<Long> ids) {
        List<BpStoreHouseAddBean> beans=new ArrayList<>();
        List<BpStoreHouse> list = dao.findByIds(ids);
        List<BpMonitoringPointRel> relList = relDao.findByRefTypeAndRefIds("store_house", ids);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        Map<Long,List<BpMonitoringPointRel>> reMap=new HashMap();
        Map<Long, MhMonitoringPointBean> beanMap=new HashMap<>();
        if (!CollectionUtils.isEmpty(relList)) {
            List<Long> pointIds = relList.stream().map(BpMonitoringPointRel::getMonitoringPointId).collect(Collectors.toList());
            List<MhMonitoringPointBean> monitoringPoints = mhMonitoringPointService.findByIds(pointIds);
            beanMap = monitoringPoints.stream().collect(Collectors.toMap(MhMonitoringPointBean::getId, e -> e));
            for (BpMonitoringPointRel rel : relList) {
                if (reMap.get(rel.getRefId())!=null) {
                    List<BpMonitoringPointRel> bpMonitoringPointRels = reMap.get(rel.getRefId());
                    bpMonitoringPointRels.add(rel);
                }else {
                    List<BpMonitoringPointRel> bpMonitoringPointRels=new ArrayList<>();
                    bpMonitoringPointRels.add(rel);
                    reMap.put(rel.getRefId(),bpMonitoringPointRels);
                }
            }
        }
        List<Long> majorHazardIds = list.stream().map(BpStoreHouse::getMajorHazardId).collect(Collectors.toList());
        Map<Long,MhMajorHazard> map=new HashMap<>();
        if (!CollectionUtils.isEmpty(majorHazardIds)) {
            List<MhMajorHazard> hazardList = mhMajorHazardDao.findByIds(majorHazardIds);
            if (!CollectionUtils.isEmpty(hazardList)){
                map = hazardList.stream().collect(Collectors.toMap(MhMajorHazard::getId, e -> e));
            }
        }
        List<Long> parentIds = list.stream().filter(house -> house.getParentId() != null).distinct().map(BpStoreHouse::getParentId).collect(Collectors.toList());
        Map<Long, BpStoreHouse> houseMap=new HashMap<>();
        if (!CollectionUtils.isEmpty(parentIds)) {
            List<BpStoreHouse> houses = dao.findByIds(parentIds);
            houseMap = houses.stream().collect(Collectors.toMap(BpStoreHouse::getId, e -> e));
        }

        for (BpStoreHouse b : list) {
            BpStoreHouseAddBean h = new BpStoreHouseAddBean();
            if (b.getAutoSprayFlag() != null) {
                if (b.getAutoSprayFlag().equals("Y")) {
                    h.setAutoSprayFlag(b.getAutoSprayFlag());
                    h.setAutoSprayFlagName("是");
                }
                if (b.getAutoSprayFlag().equals("N")) {
                    h.setAutoSprayFlag(b.getAutoSprayFlag());
                    h.setAutoSprayFlagName("否");
                }
            }

            h.setCode(b.getCode());
            h.setDesignStock(b.getDesignStock());
            h.setFireDangerType(b.getFireDangerType());
            if (b.getFireWallFlag() != null) {
                if (b.getFireWallFlag().equals("Y")) {
                    h.setFireWallFlag(b.getFireWallFlag());
                    h.setFireWallFlagName("有");
                }
                if (b.getFireWallFlag().equals("N")) {
                    h.setFireWallFlag(b.getFireWallFlag());
                    h.setFireWallFlagName("无");
                }
            }

            if (b.getHazardChemStoreFlag() != null) {
                if (b.getHazardChemStoreFlag().equals("Y")) {
                    h.setHazardChemStoreFlag(b.getHazardChemStoreFlag());
                    h.setHazardChemStoreFlagName("是");
                }
                if (b.getHazardChemStoreFlag().equals("N")) {
                    h.setHazardChemStoreFlag(b.getHazardChemStoreFlag());
                    h.setHazardChemStoreFlagName("否");
                }
            }
            // h.setHouseNo(b.getHouseNo());
            if (b.getHypertoxicHazardChemStoreFlag() != null) {
                if (b.getHypertoxicHazardChemStoreFlag().equals("Y")) {
                    h.setHypertoxicHazardChemStoreFlag(b.getHypertoxicHazardChemStoreFlag());
                    h.setHypertoxicHazardChemStoreFlagName("是");
                }
                if (b.getHypertoxicHazardChemStoreFlag().equals("N")) {
                    h.setHypertoxicHazardChemStoreFlag(b.getHypertoxicHazardChemStoreFlag());
                    h.setHypertoxicHazardChemStoreFlagName("否");
                }
            }
            h.setId(b.getId());
            h.setLocation(b.getLocation());
            h.setStartUseTime(b.getStartUseTime());
            if (b.getLowTemperatureStoreFlag() != null) {
                if (b.getLowTemperatureStoreFlag().equals("Y")) {
                    h.setLowTemperatureStoreFlag(b.getLowTemperatureStoreFlag());
                    h.setLowTemperatureStoreFlagName("是");
                }
                if (b.getLowTemperatureStoreFlag().equals("N")) {
                    h.setLowTemperatureStoreFlag(b.getLowTemperatureStoreFlag());
                    h.setLowTemperatureStoreFlagName("否");
                }
            }
            if (b.getMajorHazardId() != null) {
                MhMajorHazard one = map.get(b.getMajorHazardId());
                if (one != null) {
                    h.setMajorHazardUnit(one.getName());
                }
            }
            h.setMajorHazardId(b.getMajorHazardId());
            h.setMajorHazardUnitCode(b.getMajorHazardUnitCode());
            if (b.getMajorMonitoringChemFlag() != null) {
                if (b.getMajorMonitoringChemFlag().equals("Y")) {
                    h.setMajorMonitoringChemFlag(b.getMajorMonitoringChemFlag());
                    h.setMajorMonitoringChemFlagName("是");
                }
                if (b.getMajorMonitoringChemFlag().equals("N")) {
                    h.setMajorMonitoringChemFlag(b.getMajorMonitoringChemFlag());
                    h.setMajorMonitoringChemFlagName("否");
                }
            }
            h.setName(b.getName());
            h.setStartUseTime(b.getStartUseTime());
            h.setStoreHouseForm(b.getStoreHouseForm());
            h.setStoreHouseSize(b.getStoreHouseSize());
            ArrayList<MhMonitoringPointBean> objects = new ArrayList<>();
            List<BpMonitoringPointRel> all1 = reMap.get(b.getId());
            if (all1 != null) {
                for (BpMonitoringPointRel bpMonitoringPointRel : all1) {
                    if (bpMonitoringPointRel.getRefId() == b.getId()
                            && bpMonitoringPointRel.getRefType().equals("store_house")) {
                        MhMonitoringPointBean byId = beanMap.get(bpMonitoringPointRel.getMonitoringPointId());
                        objects.add(byId);
                    }
                }
            }
            h.setParentId(b.getParentId());
            if (b.getParentId() != null && houseMap.get(b.getParentId()) != null) {
                h.setParentName(houseMap.get(b.getParentId()).getName());
            }
            h.setMhMonitoringPointBeans(objects);
            h.setTypeFlag(b.getTypeFlag());
            beans.add(h);
        }
        return beans;
    }

    /**
     * 获取仓库列表
     *
     * @return
     */
    @Override
    public List<BpStoreHouseListBean> getList(Integer typeFlag) {
        List<BpStoreHouse> all = dao.findByTypeFlag(typeFlag);
        List<BpStoreHouseListBean> list = all.stream().map(r -> {
            BpStoreHouseListBean bean = new BpStoreHouseListBean();
            BeanUtils.copyProperties(r, bean);
            return bean;
        }).collect(Collectors.toList());
        Map<Long, BpStoreHouseListBean> map = list.stream().collect(Collectors.toMap(BpStoreHouseListBean::getId, r -> r));
        List<BpStoreHouseListBean> returnList = new ArrayList<>();
        for (BpStoreHouseListBean listBean : list) {
            Long parentId = listBean.getParentId();
            if (parentId != null) {
                BpStoreHouseListBean bean = map.get(parentId);
                List<BpStoreHouseListBean> childrenList = bean.getChildrenList();
                childrenList = childrenList == null ? Lists.newArrayList() : childrenList;
                childrenList.add(listBean);
                bean.setChildrenList(childrenList);
            }
        }
        if (!CollectionUtils.isEmpty(list)) {
            for (BpStoreHouseListBean b : list) {
                if (b.getParentId() == null) {
                    returnList.add(b);
                }
            }
        }
        return returnList;
    }

    /**
     * 动态分页展示监测点列表
     *
     * @param pageable
     * @return
     */
    @Override
    public ResultBean pageMhPoint(Pageable pageable, Long parentId) {
        List<MhMonitoringRealTimeListBean> s = this.getMhPointBeanList();
        List<MhMonitoringRealTimeListBean> beanList = new ArrayList<>();
        if (parentId != null) {
            //返回上一级仓库的所有监测点
            List<BpMonitoringPointRel> refList = relDao.findByRefTypeAndRefId("store_house", parentId);
            if (!CollectionUtils.isEmpty(refList)) {
                for (BpMonitoringPointRel ref : refList) {
                    if (!CollectionUtils.isEmpty(s)) {
                        for (MhMonitoringRealTimeListBean bean : s) {
                            if (bean.getId().equals(ref.getMonitoringPointId())) {
                                beanList.add(bean);
                            }
                        }
                    }
                }
            }
            if (CollectionUtils.isEmpty(beanList)) {
                return ResultBean.success(new ArrayList<>());
            } else {
                List<MhMonitoringRealTimeListBean> resultList = beanList.stream().sorted((a, b) -> b.getId().intValue() - a.getId().intValue()).collect(Collectors.toList());
                List<MhMonitoringRealTimeListBean> list = PageableUtil.getList(pageable.getPageNumber(), pageable.getPageSize(), resultList);
                return ResultBean.pageData(list, beanList.size());
            }
        } else {
            //返回所有监测点
            if (CollectionUtils.isEmpty(s)) {
                return ResultBean.success(new ArrayList<>());
            } else {
                List<MhMonitoringRealTimeListBean> resultList = s.stream().sorted((a, b) -> b.getId().intValue() - a.getId().intValue()).collect(Collectors.toList());
                List<MhMonitoringRealTimeListBean> list = PageableUtil.getList(pageable.getPageNumber(), pageable.getPageSize(), resultList);
                return ResultBean.pageData(list, s.size());
            }
        }
    }

    //获取监测点数据
    private List<MhMonitoringRealTimeListBean> getMhPointBeanList() {
        List<MhMonitoringPoint> all = mhMonitoringPointDao.findAll();
        List<MhMonitoringRealTimeListBean> s = new ArrayList<>();
        if (!CollectionUtils.isEmpty(all)) {
            for (MhMonitoringPoint m : all) {
                MhMonitoringRealTimeListBean bean = new MhMonitoringRealTimeListBean();
                bean.setId(m.getId());
                bean.setName(m.getName());
                bean.setMonitoringTypeId(m.getMhMonitoringType().getId());
                bean.setMinitoringTypeName(m.getMhMonitoringType().getName());
                bean.setPointCode(m.getPointCode());
                bean.setUnit(m.getUnit());
                bean.setLevel1Threshold(m.getLevel1Threshold());
                bean.setLevel2Threshold(m.getLevel2Threshold());
                bean.setHighValue(m.getHighValue());
                bean.setLowValue(m.getLowValue());
                bean.setPointCode(m.getPointCode());
                bean.setHighValue1(m.getHighValue1());
                bean.setHighValue2(m.getHighValue2());
                bean.setLowValue1(m.getLowValue1());
                bean.setLowValue2(m.getLowValue2());
                s.add(bean);
            }
        }
        return s;
    }

    @Override
    public List<BpStoreHouse> page() {
        /*
         * List<BpStoreArea> all = bpStoreAreaDao.findAll();
         * ArrayList<BpStoreHouse> list = new ArrayList<>();
         * for (BpStoreArea bpStoreArea : all) {
         * List<BpStoreHouse> all1 = dao.findAll();
         * for (BpStoreHouse bpStoreHouse : all1) {
         * if(bpStoreArea.getCode().equals(bpStoreHouse.getStoreAreaCode()) ){
         * list.
         * }
         * }
         * }
         */
        return null;
    }

    /**
     * 增加物资类型
     *
     * @param bean
     * @return
     */
    @Override
    public BpStoreMaterialType addType(BpStoreMaterialTypeOrUnitBean bean) {
        BpStoreMaterialType t = bpStoreMaterialTypeDao.findByName(bean.getName());
        if (t != null) {
            throw new IllegalArgumentException("物资类型已存在");
        }
        BpStoreMaterialType type = new BpStoreMaterialType();
        type.setName(bean.getName());
        type.setAmount(0);
        return bpStoreMaterialTypeDao.save(type);
    }

    /**
     * 修改物资类型
     *
     * @param bean
     * @return
     */
    @Override
    public BpStoreMaterialType updateType(BpStoreMaterialTypeOrUnitBean bean) {
        BpStoreMaterialType type = bpStoreMaterialTypeDao.findById(bean.getId()).orElseThrow(() -> new IllegalArgumentException("物资类型不存在"));
        type.setName(bean.getName());
        return bpStoreMaterialTypeDao.save(type);
    }

    /**
     * 删除物资类型
     *
     * @param id
     */
    @Override
    public void deleteTypeById(Long id) {
        Integer count = bpStoreMaterialDao.countByTypeId(id);
        if (count != null && count.intValue() > 0) {
            throw new IllegalArgumentException("该物资类型已被使用,请勿删除");
        }
        bpStoreMaterialTypeDao.deleteById(id);
    }

    /**
     * 分页展示物资类型
     *
     * @param pageable
     * @param typeFlag 0物资仓库;1危化品仓库
     * @return
     */
    @Override
    public ResultBean pageType(Pageable pageable, Integer typeFlag) {
        List<BpStoreMaterialType> all = bpStoreMaterialTypeDao.findAll();
        List<BpStoreMaterialTypeOrUnitBean> beanList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(all)) {
            for (BpStoreMaterialType type : all) {
                BpStoreMaterialTypeOrUnitBean bean = new BpStoreMaterialTypeOrUnitBean();
                bean.setId(type.getId());
                bean.setName(type.getName());
                //需求 物资仓库和危化品类型数量要分开
                if (typeFlag != null) {
                    int amount = bpStoreMaterialDao.countByTypeIdAndTypeFlag(type.getId(), typeFlag);
                    bean.setAmount(amount);
                }
                beanList.add(bean);
            }
        }
        return resultBean(pageable, beanList);
    }

    /**
     * 增加物资单位
     *
     * @param bean
     * @return
     */
    @Override
    public BpStoreMaterialUnit addUnit(BpStoreMaterialTypeOrUnitBean bean) {
        BpStoreMaterialUnit t = bpStoreMaterialUnitDao.findByName(bean.getName());
        if (t != null) {
            throw new IllegalArgumentException("物资单位已存在");
        }
        BpStoreMaterialUnit unit = new BpStoreMaterialUnit();
        unit.setName(bean.getName());
        unit.setAmount(0);
        return bpStoreMaterialUnitDao.save(unit);
    }

    /**
     * 修改物资单位
     *
     * @param bean
     * @return
     */
    @Override
    public BpStoreMaterialUnit updateUnit(BpStoreMaterialTypeOrUnitBean bean) {
        BpStoreMaterialUnit unit = bpStoreMaterialUnitDao.findById(bean.getId()).orElseThrow(() -> new IllegalArgumentException("物资单位不存在"));
        unit.setName(bean.getName());
        return bpStoreMaterialUnitDao.save(unit);
    }

    /**
     * 删除物资单位
     *
     * @param id
     */
    @Override
    public void deleteUnitById(Long id) {
        Integer count = bpStoreMaterialDao.countByUnitId(id);
        if (count != null && count.intValue() > 0) {
            throw new IllegalArgumentException("该物资单位已被使用,请勿删除");
        }
        //删除物资单位
        bpStoreMaterialUnitDao.deleteById(id);
    }

    /**
     * 分页展示物资单位
     *
     * @param pageable
     * @param typeFlag 0物资仓库;1危化品仓库
     * @return
     */
    @Override
    public ResultBean pageUnit(Pageable pageable, Integer typeFlag) {
        List<BpStoreMaterialUnit> all = bpStoreMaterialUnitDao.findAll();
        List<BpStoreMaterialTypeOrUnitBean> beanList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(all)) {
            for (BpStoreMaterialUnit unit : all) {
                BpStoreMaterialTypeOrUnitBean bean = new BpStoreMaterialTypeOrUnitBean();
                bean.setId(unit.getId());
                bean.setName(unit.getName());
                if (typeFlag != null) {
                    int amount = bpStoreMaterialDao.countByUnitIdAndTypeFlag(unit.getId(), typeFlag);
                    bean.setAmount(amount);
                }
                beanList.add(bean);
            }
        }
        return resultBean(pageable, beanList);
    }

    /**
     * 获取物资单位列表
     *
     * @return
     */
    @Override
    public List<BpStoreMaterialTypeOrUnitListBean> getUnitList() {
        List<BpStoreMaterialTypeOrUnitListBean> list = new ArrayList<>();
        List<BpStoreMaterialUnit> all = bpStoreMaterialUnitDao.findAll();
        if (!CollectionUtils.isEmpty(all)) {
            for (BpStoreMaterialUnit u : all) {
                BpStoreMaterialTypeOrUnitListBean bean = new BpStoreMaterialTypeOrUnitListBean();
                bean.setLabel(u.getName());
                bean.setValue(u.getId());
                list.add(bean);
            }

        }
        return list;
    }

    /**
     * 获取物资类型列表
     *
     * @return
     */
    @Override
    public List<BpStoreMaterialTypeOrUnitListBean> getTypeList() {
        List<BpStoreMaterialTypeOrUnitListBean> list = new ArrayList<>();
        List<BpStoreMaterialType> all = bpStoreMaterialTypeDao.findAll();
        if (!CollectionUtils.isEmpty(all)) {
            for (BpStoreMaterialType t : all) {
                BpStoreMaterialTypeOrUnitListBean bean = new BpStoreMaterialTypeOrUnitListBean();
                bean.setLabel(t.getName());
                bean.setValue(t.getId());
                list.add(bean);
            }

        }
        return list;
    }

    /**
     * 增加物资
     *
     * @param bean
     * @return
     */
    @Override
    public BpStoreMaterial addMaterial(BpStoreMaterialBean bean) {
        BpStoreMaterial m = new BpStoreMaterial();
        BeanUtils.copyProperties(bean, m);
        m.setCode(bizCodeGeneratorFacade.wuzi());
        //m.setAmount(Double.valueOf(0));
        BpStoreMaterial save = bpStoreMaterialDao.save(m);
        //更新物资类型和单位数量
        updateTypeAndUnitAmount(m.getTypeId(), m.getUnitId());
        return save;
    }

    /**
     * 修改物资
     *
     * @param bean
     * @return
     */
    @Override
    public BpStoreMaterial updateMaterial(BpStoreMaterialBean bean) {
        BpStoreMaterial m = bpStoreMaterialDao.findById(bean.getId()).orElseThrow(() -> new IllegalArgumentException("物资不存在"));
        Long unitId = m.getUnitId();
        Long typeId = m.getTypeId();
        Long houseId = m.getHouseId();
        BeanUtils.copyProperties(bean, m);
        //不更改仓库
        m.setHouseId(houseId);
        //数值单位,类型与旧数据是否一致,分两种情况 ,一致数量不需要更改
        if (unitId != null) {
            if (!unitId.equals(bean.getUnitId())) {
                //数值单位前后不一致
                BpStoreMaterialUnit oldUnit = bpStoreMaterialUnitDao.findById(unitId).orElseThrow(() -> new IllegalArgumentException("物资单位不存在"));
                BpStoreMaterialUnit newUnit = bpStoreMaterialUnitDao.findById(bean.getUnitId()).orElseThrow(() -> new IllegalArgumentException("物资单位不存在"));
                oldUnit.setAmount(oldUnit.getAmount() - 1);
                newUnit.setAmount(newUnit.getAmount() + 1);
                bpStoreMaterialUnitDao.save(oldUnit);
                bpStoreMaterialUnitDao.save(newUnit);
            }
        }

        if (typeId != null) {
            if (!typeId.equals(bean.getTypeId())) {
                //数值单位前后不一致
                BpStoreMaterialType oldType = bpStoreMaterialTypeDao.findById(typeId).orElseThrow(() -> new IllegalArgumentException("物资单位不存在"));
                BpStoreMaterialType newType = bpStoreMaterialTypeDao.findById(bean.getTypeId()).orElseThrow(() -> new IllegalArgumentException("物资单位不存在"));
                oldType.setAmount(oldType.getAmount() - 1);
                newType.setAmount(newType.getAmount() + 1);
                bpStoreMaterialTypeDao.save(oldType);
                bpStoreMaterialTypeDao.save(newType);
            }
        }

        return bpStoreMaterialDao.save(m);
    }

    /**
     * 删除物资
     *
     * @param id
     */
    @Override
    public void deleteMaterial(Long id) {
        //删除物资记录
        List<BpStoreMaterialRecord> records = bpStoreMaterialRecordDao.findByMaterialId(id);
        if (!CollectionUtils.isEmpty(records)) {
            for (BpStoreMaterialRecord record : records) {
                bpStoreMaterialRecordDao.deleteById(record.getId());
            }
        }
        BpStoreMaterial m = bpStoreMaterialDao.findById(id).orElseThrow(() -> new IllegalArgumentException("物资不存在"));
        bpStoreMaterialDao.deleteById(id);
        //更新物资类型和单位数量
        updateTypeAndUnitAmount(m.getTypeId(), m.getUnitId());
    }

    //更新物资类型和单位数量
    private void updateTypeAndUnitAmount(Long typeId, Long unitId) {
        if (typeId != null) {
            BpStoreMaterialType type = bpStoreMaterialTypeDao.findById(typeId).orElseThrow(() -> new IllegalArgumentException("物资类型不存在"));
            type.setAmount(bpStoreMaterialDao.countByTypeId(typeId));
            bpStoreMaterialTypeDao.save(type);
        }
        if (unitId != null) {
            BpStoreMaterialUnit unit = bpStoreMaterialUnitDao.findById(unitId).orElseThrow(() -> new IllegalArgumentException("物资单位不存在"));
            unit.setAmount(bpStoreMaterialDao.countByUnitId(unitId));
            bpStoreMaterialUnitDao.save(unit);
        }
    }

    /**
     * 查看物资
     *
     * @param id
     * @return
     */
    @Override
    public BpStoreMaterialBean getMaterialById(Long id) {
        BpStoreMaterial m = bpStoreMaterialDao.findById(id).orElseThrow(() -> new IllegalArgumentException("物资不存在"));
        BpStoreMaterialBean bean = new BpStoreMaterialBean();
        BeanUtils.copyProperties(m, bean);
        //仓库名称
        if (m.getHouseId() != null) {
            BpStoreHouse house = dao.findById(m.getHouseId()).orElseThrow(() -> new IllegalArgumentException("仓库不存在"));
            bean.setHouseName(house.getName());
        }
        //物资类型名称
        if (m.getTypeId() != null) {
            bean.setTypeName(bpStoreMaterialTypeDao.getOne(m.getTypeId()).getName());
        }
        //物资单位名称
        if (m.getUnitId() != null) {
            bean.setUnitName(bpStoreMaterialUnitDao.getOne(m.getUnitId()).getName());
        }
        //是否为危化品
        if (StringUtils.isNotBlank(m.getChemProductFlag())) {
            if (m.getChemProductFlag().equals("Y")) {
                bean.setChemProductFlag("是");
            } else {
                bean.setChemProductFlag("否");
            }
        }
        //危化品名称
        if (m.getChemProductId() != null) {
            Optional<MhMajorHazardChemProduct> byId = mhMajorHazardChemProductDao.findById(m.getChemProductId());
            if (byId.isPresent()) {
                bean.setChemProductName(byId.get().getName());
            }
        }

        if (m.getAreaId()!=null){
            bean.setAreaName(districtService.findById(m.getAreaId()).getName());
        }
        if (m.getResponsibleDeptId()!=null){
            bean.setResponsibleDeptName(bpDepartDao.findDepartNameById(m.getResponsibleDeptId()));
        }
        bean.setAmount(convert(m.getAmount()));
        return bean;
    }

    /**
     * 分页展示物资
     *
     * @param pageable
     * @param huoseId
     * @return
     */
    @Override
    public ResultBean pageMaterial(Pageable pageable, Long huoseId, Integer typeFlag, BpStoreMaterialSearchBean condition) {
        List<BpStoreHouse> hList = new ArrayList<>();
        if (huoseId != null) {
            List<BpStoreHouse> houses = dao.findAll();
            if (!CollectionUtils.isEmpty(houses)) {
                List<Long> houseIdList = houses.stream().map(BpStoreHouse::getId).distinct().collect(Collectors.toList());
                Map<Long, BpStoreHouse> housesMap = houses.stream().collect(Collectors.toMap(e -> e.getId(), e -> e));
                if (houseIdList.contains(huoseId)) {
                    hList.add(housesMap.get(huoseId));
                    getParentNode(hList, houses, huoseId);
                }
            }
        } else {
            // 0显示物资仓库,1显示危化品仓库
            hList = dao.findByTypeFlag(typeFlag);
        }
        List<BpStoreMaterialBean> beanList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(hList)) {
            for (BpStoreHouse h : hList) {
                //获取仓库下的物资
                //查询条件不同现在分为危化品和物资
                // 0显示物资仓库,1显示危化品仓库
                List<BpStoreMaterial> mL = null;
                if (1 == typeFlag) {
                    mL = bpStoreMaterialDao.findchemProduct(h.getId(), condition.getChemProductId(), condition.getNameOrCode(), condition.getTypeId());
                } else if (0 == typeFlag) {
                    mL = bpStoreMaterialDao.findByParams(h.getId(), condition.getNameOrCode(), condition.getTypeId());
                }
                if (!CollectionUtils.isEmpty(mL)) {
                    for (BpStoreMaterial material : mL) {
                        BpStoreMaterialBean bean = new BpStoreMaterialBean();
                        bean.setId(material.getId());
                        bean.setCode(material.getCode());
                        bean.setName(material.getName());
                        bean.setHouseId(material.getHouseId());
                        bean.setTypeId(material.getTypeId());
                        bean.setUnitId(material.getUnitId());
                        bean.setAmount(convert(material.getAmount()));
                        bean.setChemProductFlag(material.getChemProductFlag());
                        bean.setChemProductId(material.getChemProductId());
                        bean.setRemark(material.getRemark());
                        bean.setEndTime(material.getEndTime());
                        //仓库名称
                        if (material.getHouseId() != null) {
                            bean.setHouseName(dao.getOne(material.getHouseId()).getName());
                        }
                        //物资类型名称
                        if (material.getTypeId() != null) {
                            bean.setTypeName(bpStoreMaterialTypeDao.getOne(material.getTypeId()).getName());
                        }
                        //物资单位名称
                        if (material.getUnitId() != null) {
                            bean.setUnitName(bpStoreMaterialUnitDao.getOne(material.getUnitId()).getName());
                        }
                        //危化品名称
                        if (material.getChemProductId() != null) {
                            Optional<MhMajorHazardChemProduct> byId = mhMajorHazardChemProductDao.findById(material.getChemProductId());
                            if (byId.isPresent()) {
                                bean.setChemProductName(byId.get().getName());
                            }
                        }
                        beanList.add(bean);
                    }
                }
            }
            List<BpStoreMaterialBean> resultList = beanList.stream().sorted((a, b) -> b.getId().intValue() - a.getId().intValue()).collect(Collectors.toList());
            List<BpStoreMaterialBean> list = PageableUtil.getList(pageable.getPageNumber(), pageable.getPageSize(), resultList);
            return ResultBean.pageData(list, beanList.size());
        } else {
            return ResultBean.pageData(new ArrayList<>(), 0);
        }
    }


    /**
     * app展示物资
     *
     * @param pageable
     * @return
     */
    @Override
    public ResultBean pageNewMaterial(Pageable pageable,BpStoreMaterialSearchBean condition) {
        List<BpStoreMaterialBean> beanList = new ArrayList<>();
        //获取仓库下的物资
        //查询条件不同现在分为危化品和物资
        // 0显示物资仓库,1显示危化品仓库
        List<BpStoreMaterial> mL = null;
        mL = bpStoreMaterialDao.findAppByParams(condition.getNameOrCode(), condition.getTypeId(),0L);
        if (!CollectionUtils.isEmpty(mL)) {
            for (BpStoreMaterial material : mL) {
                BpStoreMaterialBean bean = new BpStoreMaterialBean();
                bean.setId(material.getId());
                bean.setCode(material.getCode());
                bean.setName(material.getName());
                bean.setHouseId(material.getHouseId());
                bean.setTypeId(material.getTypeId());
                bean.setUnitId(material.getUnitId());
                bean.setAmount(convert(material.getAmount()));
                bean.setChemProductFlag(material.getChemProductFlag());
                bean.setChemProductId(material.getChemProductId());
                bean.setRemark(material.getRemark());
                //仓库名称
                if (bean.getHouseId() != null) {
                    bean.setHouseName(dao.getOne(bean.getHouseId()).getName());
                }
                //物资类型名称
                if (material.getTypeId() != null) {
                    bean.setTypeName(bpStoreMaterialTypeDao.getOne(material.getTypeId()).getName());
                }
                //物资单位名称
                if (material.getUnitId() != null) {
                    bean.setUnitName(bpStoreMaterialUnitDao.getOne(material.getUnitId()).getName());
                }
                //危化品名称
                if (material.getChemProductId() != null) {
                    Optional<MhMajorHazardChemProduct> byId = mhMajorHazardChemProductDao.findById(material.getChemProductId());
                    if (byId.isPresent()) {
                        bean.setChemProductName(byId.get().getName());
                    }
                }
                beanList.add(bean);
            }
        }

        List<BpStoreMaterialBean> list = PageableUtil.getList(pageable.getPageNumber(), pageable.getPageSize(), beanList);
        return ResultBean.pageData(list, beanList.size());
    }

    private void getParentNode(List<BpStoreHouse> childMenu, List<BpStoreHouse> importList, Long pid) {
        importList.stream()
                //过滤出父id等于参数的id
                .filter(house -> house.getParentId() != null && house.getParentId().equals(pid))
                .forEach(house -> {
                    //递归遍历下一级
                    getParentNode(childMenu, importList, house.getId());
                    //添加
                    childMenu.add(house);
                });
    }

    /**
     * 出库/入库/盘点
     *
     * @param bean
     * @return
     */
    @Override
    public BpStoreMaterialRecord recordMaterial(BpStoreMaterialRecordBean bean) {
        BpStoreMaterial m = bpStoreMaterialDao.findById(bean.getMaterialId()).orElseThrow(() -> new IllegalArgumentException("物资不存在"));
        BpStoreMaterialRecord record = new BpStoreMaterialRecord();
        BeanUtils.copyProperties(bean, record);
        //出库/入库单号
        record.setOrderNo(bean.getOrderNo());
        //旧物资总量
        if (bean.getMaterialId() != null) {
            record.setOldAmount(bpStoreMaterialDao.getOne(bean.getMaterialId()).getAmount());
        }
        // 附件
        if (bean.getAttachment() != null) {
            record.setAttachmentId(bean.getAttachment().getId());
        }
        String type = bean.getType();
        //出库入库传的是数据字典id
        if (bean.getTypeId() != null) {
            type = baseTypeGroupItemDao.getNameById(bean.getTypeId());
            record.setType(type);
        }
        if (type.equals("入库")) {
            if (bean.getChangeAmount() == null) {
                throw new IllegalArgumentException(type + "数量不能为空");
            }
            if (bean.getChangeAmount() < 0 || bean.getChangeAmount() == 0) {
                throw new IllegalArgumentException("入库数量必须大于0");
            }
            //入库数量
            record.setChangeAmount(bean.getChangeAmount());
            //入库后的物资数量
            record.setNewAmount(record.getOldAmount() + bean.getChangeAmount());
            m.setAmount(record.getOldAmount() + bean.getChangeAmount());
        } else if (type.equals("出库") || type.equals("报废")) {
            if (bean.getChangeAmount() == null) {
                throw new IllegalArgumentException(type + "数量不能为空");
            }
            if (bean.getChangeAmount() < 0 || bean.getChangeAmount() == 0) {
                throw new IllegalArgumentException(type + "数量必须大于0");
            }
            if (bean.getChangeAmount() > record.getOldAmount()) {
                throw new IllegalArgumentException(type + "数量不可大于物资库存数量");
            }
            //出库数量
            record.setChangeAmount(bean.getChangeAmount());
            //出库后的物资数量
            record.setNewAmount(record.getOldAmount() - bean.getChangeAmount());
            m.setAmount(record.getOldAmount() - bean.getChangeAmount());
        } else if (type.equals("盘点")) {
            if (bean.getNewAmount() == null) {
                throw new IllegalArgumentException(type + "数量不能为空");
            }
            if (record.getNewAmount() < 0) {
                throw new IllegalArgumentException("盘点数量不可为负");
            }
            //盘点数量变化
            record.setChangeAmount(record.getNewAmount() - record.getOldAmount());
            m.setAmount(record.getNewAmount());
        }
        bpStoreMaterialDao.save(m);
        BpStoreMaterialRecord save = bpStoreMaterialRecordDao.save(record);
        return save;
    }

    /**
     * 分页展示物资记录
     *
     * @param pageable
     * @param materialId
     * @return
     */
    @Override
    public ResultBean pageMaterialRecord(Pageable pageable, Long materialId) {
        List<BpStoreMaterialRecord> rList = bpStoreMaterialRecordDao.findByMaterialId(materialId);
        List<BpStoreMaterialRecordListBean> beanList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(rList)) {
            for (BpStoreMaterialRecord record : rList) {
                BpStoreMaterialRecordListBean bean = new BpStoreMaterialRecordListBean();
                bean.setId(record.getId());
                bean.setDate(record.getDate());
                bean.setRegistrationName(getPeopleNameById(record.getRegistrationId()));
                bean.setType(record.getType());
                String s = String.format("%.2f", record.getNewAmount() - record.getOldAmount());
                if (record.getNewAmount() - record.getOldAmount() > 0) {
                    bean.setChangeAmount("+" + s);
                } else {
                    bean.setChangeAmount(s);
                }
                bean.setNewAmount(convert(record.getNewAmount()));
                beanList.add(bean);
            }
        }
        List<BpStoreMaterialRecordListBean> resultList = beanList.stream().sorted((a, b) -> b.getId().intValue() - a.getId().intValue()).collect(Collectors.toList());
        List<BpStoreMaterialRecordListBean> list = PageableUtil.getList(pageable.getPageNumber(), pageable.getPageSize(), resultList);
        return ResultBean.pageData(list, beanList.size());
    }

    /**
     * 查看物资记录
     *
     * @param recordId
     * @return
     */
    @Override
    public BpStoreMaterialRecordBean getMaterialRecord(Long recordId) {
        BpStoreMaterialRecord record = bpStoreMaterialRecordDao.findById(recordId).orElseThrow(() -> new IllegalArgumentException("物资记录不存在"));
        BpStoreMaterialRecordBean bean = new BpStoreMaterialRecordBean();
        BeanUtils.copyProperties(record, bean);
        //物资名称
        if (record.getMaterialId() != null) {
            Optional<BpStoreMaterial> byId = bpStoreMaterialDao.findById(record.getMaterialId());
            if (byId.isPresent()) {
                BpStoreMaterial material = byId.get();
                if (StringUtils.isNotBlank(material.getName())) {
                    bean.setMaterialName(material.getName());
                } else {
                    //危化品物资用危化品名称
                    if (material.getChemProductId() != null) {
                        Optional<MhMajorHazardChemProduct> oc = mhMajorHazardChemProductDao.findById(material.getChemProductId());
                        if (oc.isPresent()) {
                            bean.setMaterialName(oc.get().getName());
                        }
                    }
                }
            }
//            bean.setMaterialName(bpStoreMaterialDao.getOne(record.getMaterialId()).getName());
        }
        //仓管员
        if (record.getWarehouseKeeperId() != null) {
            bean.setWarehouseKeeperName(getPeopleNameById(record.getWarehouseKeeperId()));
        }
        //交货单位
        if (record.getDeliveryUnitId() != null) {
            bean.setDeliveryUnitName(getContractorNameById(record.getDeliveryUnitId()));
        }
        //运输单位
        if (record.getTransportUnitId() != null) {
            bean.setTransportUnitName(getContractorNameById(record.getTransportUnitId()));
        }
        //登记员
        if (record.getRegistrationId() != null) {
            bean.setRegistrationName(getPeopleNameById(record.getRegistrationId()));
        }
        //附件
        if (record.getAttachmentId() != null) {
            bean.setAttachment(attachmentRepositoryService.findByIdIntoBean(record.getAttachmentId()));
        }
        bean.setOldAmount(convert(record.getOldAmount()));
        bean.setChangeAmount(convert(record.getChangeAmount()));
        bean.setNewAmount(convert(record.getNewAmount()));
        return bean;
    }


    //根据id查人员名称
    private String getPeopleNameById(Long id) {
        if (id != null) {
            Optional<BaseUser> byId = baseUserDao.findById(id);
            if (byId.isPresent()) {
                return byId.get().getRealName();
            } else {
                return "";
            }
        } else {
            return "";
        }
    }

    //根据id查承包商名称
    private String getContractorNameById(Long id) {
        if (id != null) {
            Optional<BpContractor> byId = bpContractorDao.findById(id);
            if (byId.isPresent()) {
                return byId.get().getCompanyName();
            } else {
                return "";
            }
        } else {
            return "";
        }
    }

    //返回分页结果
    private ResultBean resultBean(Pageable pageable, List<BpStoreMaterialTypeOrUnitBean> beanList) {
        List<BpStoreMaterialTypeOrUnitBean> resultList = beanList.stream().sorted((a, b) -> b.getId().intValue() - a.getId().intValue()).collect(Collectors.toList());
        List<BpStoreMaterialTypeOrUnitBean> list = PageableUtil.getList(pageable.getPageNumber(), pageable.getPageSize(), resultList);
        return ResultBean.pageData(list, beanList.size());
    }

    private double convert(double value) {
        //long l1 = Math.round(value * 100); //四舍五入
        //double ret = l1 / 100.0; //注意:使用 100.0 而不是 100
        //return ret;
        // 格式处理：小数点后00，直接展示整数
        return value;
    }

    @Override
    public List<SimpleSelectListBean> findchemProductSimpleList() {
        List<Long> chemProductIds = bpStoreMaterialDao.findchemProductSimpleList();
        List<SimpleSelectListBean> listBeans = new ArrayList<>();
        for (Long chemProductId : chemProductIds) {
            SimpleSelectListBean listBean = new SimpleSelectListBean();
            String chemProductName = mhMajorHazardChemProductDao.findNameById(chemProductId);
            listBean.setValue(chemProductId);
            listBean.setLabel(chemProductName);
            listBeans.add(listBean);
        }
        return listBeans;
    }
}
